package com.kangfuqiang.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {
	public static void writeFile(byte[] bytes, String filePath) throws IOException {
		File f = new File(filePath);
//		System.out.println(f.getAbsolutePath());
		createParentPath(f);
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
		bos.write(bytes);
		bos.flush();
		bos.close();
	}

	public static boolean createParentPath(File file) {
		File parent = file.getParentFile();
		return parent.mkdirs();
	}
	
	public static boolean delete(String filePath){
		File f = new File(filePath);
		return f.delete();
	}
	
	public static boolean createNewFile(String path) throws IOException {
		File file = new File(path);
		createParentPath(file);
		return file.createNewFile();
	}


	
	public static boolean rename(File srcFile, String newName) {
		File file = new File(srcFile.getParent() + File.separator + newName);
		createParentPath(file);
		return srcFile.renameTo(file);
	}

	public static boolean cutFile(File srcFile, String descDir) {
		File file = new File(descDir + File.separator + srcFile.getName());
		createParentPath(file);
		return srcFile.renameTo(file);
	}

	public static boolean renameTo(File srcFile, File descFile) {
		createParentPath(descFile);
		return srcFile.renameTo(descFile);
	}

	/**
	 * 删除目录下的所有文件及目录；
	 * 
	 * @param folder
	 *            需要删除的目录
	 * @return 如果传入参数不是目录，返回true；如果传入参数是目录，并且删除成功，则返回true；
	 */
	public static boolean deleteDir(File folder) {
		boolean flag = true;
		if (folder.isDirectory()) {
			File[] files = folder.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					flag = deleteDir(files[i]);
				} else {
					flag = files[i].delete();
				}
				if (!flag) {
					break;
				}
			}
			flag = folder.delete();
		}
		return flag;
	}
}
